import React, { useEffect, useState, useRef, FC } from 'react'
import { DotLoading, SearchBar, Popup, CheckList, Tag, Space } from 'antd-mobile'
import { request } from 'alita'
import type { SearchBarRef } from 'antd-mobile/es/components/search-bar';
import { urlPrefix } from '@/utils/http';
import type { IdName, PageResult, Block, Supplier,Opportunity,Specialized } from '@/pages/types/type'
import styles from './index.less'
import { postRequestInit } from '@/utils/http';
import { CheckListValue } from 'antd-mobile/es/components/check-list';
import { ACCESSTOKEN } from '@/utils/authorize';
interface Opp { id: number, name: string };

export  const OpportunitySelector = ({ value, onChange, popupVisible, setPopupVisible }: { value?: Opp, popupVisible: boolean, onChange?: (val: Opp) => void | undefined, setPopupVisible: (x: boolean) => void }) => {
    
    const [opportunities, setOpportunities] = useState<Opportunity[]>([])

    const [searchText, setSearchText] = useState<string | undefined>('')

    const [searching, setSearching] = useState<boolean | undefined>(false);
    const searchRef = useRef<SearchBarRef>(null);

    function search(name?: string) {
        setSearching(true);
        const nativeElement = searchRef.current?.nativeElement;
        const attr = 'disabled';
        nativeElement?.setAttribute(attr, 'true');
        request('/api/opportunity-search', {
            headers: { 'Authorization': `Bearer ${localStorage.getItem(ACCESSTOKEN)}` }, method: 'post', data: { size:500,page:0, name }
        }
        ).then(({ data, code, msg }: PageResult<Opportunity>) => {
            setOpportunities(code === 0 && data ? data : [])
            if (code !== 0) console.error(msg);

            nativeElement?.removeAttribute(attr);
            setSearching(false);
        })
    }
    useEffect(search,[]);
    return (
        <React.Fragment>
            {value ? value.name : '请选择商机'}
            <Popup
                visible={popupVisible}
                onMaskClick={() => { setPopupVisible(false) }}
                destroyOnClose
                bodyStyle={{ height: '50vh' }}
            >
                <div  className={styles.searchBarContainer}>
                    <SearchBar style={{marginTop:'10px',marginLeft:'3px',marginRight:'3px'}} placeholder='输入商机名称搜索' ref={searchRef}
                        value={searchText}
                        onChange={v => { setSearchText(v) }}
                        onSearch={search}
                    />
                </div>
                {searching && <DotLoading />}
                <div className={styles.checkListContainer}>
                    <CheckList
                        className={styles.myCheckList}
                        defaultValue={value ? [value .id] : []}
                        onChange={val => {
                            const prs = (x:Opportunity)=>x.id ===val[0];
                            if (opportunities.some(prs)) {
                                const opp = opportunities.filter(prs)[0]
                                onChange?.({ id: opp.id, name: opp.name })
                            }
                            setPopupVisible(false)
                        }}
                    >{opportunities.map(({ id, name, region }) => (
                        <CheckList.Item key={id} value={ id}>
                            {name} ({region.label})
                        </CheckList.Item>
                    ))}
                    </CheckList>
                </div>
            </Popup>
        </React.Fragment>
    )
}

export const BlockSelector:
    FC<{
        value?: IdName, popupVisible:
            boolean, onChange?: (val: IdName) => void | undefined, setPopupVisible: (x: boolean) => void
    }>
    = ({ value, onChange, popupVisible, setPopupVisible }) => {

        const [blocks, setBlocks] = useState<Block[]>([])
        const [searchText, setSearchText] = useState<string | undefined>('')
        const [searching, setSearching] = useState<boolean | undefined>(false);
        const searchRef = useRef<SearchBarRef>(null);
        function search(name?: string) {
            setSearching(true);
            const nativeElement = searchRef.current?.nativeElement;
            const attr = 'disabled';
            nativeElement?.setAttribute(attr, 'true');
            let response: Promise<Response> = fetch(`${urlPrefix}/api/block-search`, postRequestInit({ name, page: 0, size: 20, level: 'project' }))
            response.then((rsp: Response) => {
                if (rsp.ok) {
                    rsp.json().then(({ data, code, msg }: PageResult<Block>) => {
                        if (code === 0) {
                            if (data) setBlocks(data);
                        } else {
                            setBlocks([]);
                            console.error(msg);
                        }
                        nativeElement?.removeAttribute(attr);
                        setSearching(false);
                    })
                }
            })
        }

        useEffect(() => search(), []);

        return (
            <React.Fragment>
                {value ? value.name : '请选择项目'}
                <Popup
                    visible={popupVisible}
                    onMaskClick={() => { setPopupVisible(false) }}
                    destroyOnClose
                    bodyStyle={{ height: '65vh' }}
                >
                    <div className={styles.searchBarContainer}>
                        <SearchBar placeholder='没有列出？尝试输入项目名称搜索' ref={searchRef}
                            value={searchText}
                            onChange={(v:string) => { setSearchText(v) }}
                            onSearch={search}
                        />
                    </div>
                    {searching && <DotLoading />}
                    <div className={styles.checkListContainer}>
                        <CheckList
                            className={styles.myCheckList}
                            defaultValue={value ? [`${value.id}`] : []}
                            onChange={(val:CheckListValue[]) => {
                                if (blocks.some(({ id }) => id === val[0])) {
                                    const { id, name, code }: Block = blocks.filter(({ id }) => id === val[0])[0];
                                    onChange?.({ id: id, name: `${code ? `${code}-` : ''}${name}` })
                                    setPopupVisible(false)
                                }
                            }}
                        >{blocks.map(({ code, id, name, childrenCount }) => (
                            <CheckList.Item disabled={childrenCount< 1} key={id} value={id}>
                                {code && <Tag color={'primary'}>{code}</Tag>} {name}
                            </CheckList.Item>
                        ))}
                        </CheckList>
                    </div>
                </Popup>
            </React.Fragment>
        )
    }

export const SupplierSelector : FC<{ value?: IdName,   onChange?: (val: IdName) => void | undefined,  useRange?:string }> = ({ value, onChange,useRange } ) => {

    const [suppliers, setSuppliers] = useState<Supplier[]>([])
    const [visible, setVisible] = useState<boolean>(false);

    const [searchText, setSearchText] = useState<string | undefined>('')
    const [searching, setSearching] = useState<boolean | undefined>(false);
    const searchRef = useRef<SearchBarRef>(null);
    function search(name?: string) {
        setSearching(true);
        const nativeElement = searchRef.current?.nativeElement;
        const attr = 'disabled';
        nativeElement?.setAttribute(attr, 'true');
        let response: Promise<Response> = fetch(`${urlPrefix}/api/supplier-search`, postRequestInit({ name,page:0,size:20 ,level:'self',useRange }))
        response.then(( rsp:Response )=>{
            if(rsp.ok){
                rsp.json().then(({ data, code, msg }: PageResult<Supplier>) => {
                    if (code === 0) {
                        if (data) setSuppliers(data);
                    } else {
                        setSuppliers([]);
                        console.error(msg);
                    }
                    nativeElement?.removeAttribute(attr);
                    setSearching(false);
                })
            }
        })
    }
    useEffect(()=>search(),[]);
    return (
        <React.Fragment>
            {value ?  <React.Fragment> <Space onClick={()=>setVisible(true)}>{value.name}</Space></React.Fragment>:
            <React.Fragment><Space  onClick={()=>setVisible(true)}>请选择供应商</Space> </React.Fragment> }
            <Popup
                visible={visible}
                onMaskClick={() => { setVisible(false) }}
                destroyOnClose
                bodyStyle={{ height: '65vh' }}
            >
                <div className={styles.searchBarContainer}>
                    <SearchBar placeholder='没有列出？尝试输入供应商名称搜索' ref={searchRef}
                        value={searchText}
                        onChange={v => { setSearchText(v) }}
                        onSearch={search}
                    />
                </div>
                {searching && <DotLoading />}
                <div className={styles.checkListContainer}>
                    <CheckList
                        className={styles.myCheckList}
                        defaultValue={value ? [ value.id] : []}
                        onChange={val => {
                            if (suppliers.some(({ id }) => id === val[0])) {
                                const {id,name }:Supplier =suppliers.filter(({ id }) => id === val[0])[0];
                                onChange?.({ id,name })
                                setVisible(false)
                            }
                        }}
                    >{suppliers.map(({ id, name,children }) => (
                        <CheckList.Item disabled={children.length <1 } key={id} value={id}>
                             {name}
                        </CheckList.Item>
                    ))}
                    </CheckList>
                </div>
            </Popup>
        </React.Fragment>
    )
}

export const SpecializedSelector :
    FC<{ value?: IdName, popupVisible:  boolean,  onChange?: (val: IdName) => void | undefined,  setPopupVisible: (x: boolean) => void,useRange?:string }> = ({ value, onChange, popupVisible, setPopupVisible,useRange } ) => {

    const [specializeds, setSpecializeds] = useState<Specialized[]>([])

    const [searchText, setSearchText] = useState<string | undefined>('')
    const [searching, setSearching] = useState<boolean | undefined>(false);
    const searchRef = useRef<SearchBarRef>(null);
    function search(name?: string) {
        setSearching(true);
        const nativeElement = searchRef.current?.nativeElement;
        const attr = 'disabled';
        nativeElement?.setAttribute(attr, 'true');
        let response: Promise<Response> = fetch(`${urlPrefix}/api/specialized-search`, postRequestInit({ name,page:0,size:20,useRange /*如有必要，在此增加固定条件*/ }))
        response.then(( rsp:Response )=>{
            if(rsp.ok){
                rsp.json().then(({ data, code, msg }: PageResult<Specialized>) => {
                    if (code === 0) {
                        if (data) setSpecializeds(data);
                    } else {
                        setSpecializeds([]);
                        console.error(msg);
                    }
                    nativeElement?.removeAttribute(attr);
                    setSearching(false);
                })
            }
        })
    }
    useEffect(()=>search(),[]);
    return (
        <React.Fragment>
            {value ? value.name : '请选择运营专项'}
            <Popup
                visible={popupVisible}
                onMaskClick={() => { setPopupVisible(false) }}
                destroyOnClose
                bodyStyle={{ height: '65vh' }}
            >
                <div className={styles.searchBarContainer}>
                    <SearchBar placeholder='没有列出？尝试输入运营专项名称搜索' ref={searchRef}
                        value={searchText}
                        onChange={v => { setSearchText(v) }}
                        onSearch={search}
                    />
                </div>
                {searching && <DotLoading />}
                <div className={styles.checkListContainer}>
                    <CheckList
                        className={styles.myCheckList}
                        defaultValue={value ? [ value.id] : []}
                        onChange={val => {
                            if (specializeds.some(({ id }) => id === val[0])) {
                                const {id,name }:Specialized =specializeds.filter(({ id }) => id === val[0])[0];
                                onChange?.({ id,name })
                                setPopupVisible(false)
                            }
                        }}
                    >{specializeds.map(({ id, name,yearly }) => (
                        <CheckList.Item  key={id} value={id}>
                             [{yearly}]-{name}
                        </CheckList.Item>
                    ))}
                    </CheckList>
                </div>
            </Popup>
        </React.Fragment>
    )
}

export const LiaisonSelector :
    FC<{ value?: IdName,   onChange?: (val: IdName) => void | undefined,  
        customer?:number,excludeCustomer?:number }>
         = ({ value, onChange,customer, excludeCustomer } ) => {

    const [suppliers, setSuppliers] = useState<{id:number,name:string}[]>([])
    const [visible, setVisible] = useState<boolean>(false);

    const [searchText, setSearchText] = useState<string | undefined>('')
    const [searching, setSearching] = useState<boolean | undefined>(false);
    const searchRef = useRef<SearchBarRef>(null);
    function search(name?: string) {
        setSearching(true);
        const nativeElement = searchRef.current?.nativeElement;
        const attr = 'disabled';
        nativeElement?.setAttribute(attr, 'true');
        let response: Promise<Response> = fetch(`${urlPrefix}/api/liaison-search`, postRequestInit({ name,page:0,size:20 ,level:'self',customer,excludeCustomer }))
        response.then(( rsp:Response )=>{
            if(rsp.ok){
                rsp.json().then(({ data, code, msg }: PageResult<{id:number,name:string}>) => {
                    if (code === 0) {
                        if (data) setSuppliers(data);
                    } else {
                        setSuppliers([]);
                        console.error(msg);
                    }
                    nativeElement?.removeAttribute(attr);
                    setSearching(false);
                })
            }
        })
    }
    useEffect(()=>search(),[]);
    return (
        <React.Fragment>
            {value ?  <React.Fragment> <Space onClick={()=>setVisible(true)}>{value.name}</Space></React.Fragment>:
            <React.Fragment><Space  onClick={()=>setVisible(true)}>请选择联系人</Space> </React.Fragment> }
            <Popup
                visible={visible}
                onMaskClick={() => { setVisible(false) }}
                destroyOnClose
                bodyStyle={{ height: '65vh' }}
            >
                <div className={styles.searchBarContainer}>
                    <SearchBar placeholder='没有列出？尝试输入供应商名称搜索' ref={searchRef}
                        value={searchText}
                        onChange={v => { setSearchText(v) }}
                        onSearch={search}
                    />
                </div>
                {searching && <DotLoading />}
                <div className={styles.checkListContainer}>
                    <CheckList
                        className={styles.myCheckList}
                        defaultValue={value ? [ value.id] : []}
                        onChange={val => {
                            if (suppliers.some(({ id }) => id === val[0])) {
                                const {id,name } =suppliers.filter(({ id }) => id === val[0])[0];
                                onChange?.({ id,name })
                                setVisible(false)
                            }
                        }}
                    >{suppliers.map(({ id, name }) => (
                        <CheckList.Item key={id} value={id}>
                             {name}
                        </CheckList.Item>
                    ))}
                    </CheckList>
                </div>
            </Popup>
        </React.Fragment>
    )
}